﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;

namespace EpiNEXT.Presentation.Controls
{
    public class DraggableElementDecorator : AdornerDecorator
    {
        public event EventHandler Drag;
        public event EventHandler DragStart;
        public event EventHandler DragStop;

        private bool IsBeingDragged = false;

        public FrameworkElement GetContainedElement()
        {
            ElementDesignBorder border = this.Child as ElementDesignBorder;
            if (border != null)
            {
                FrameworkElement element = border.Content as FrameworkElement;
                if (element != null)
                {
                    return element;
                }
            }

            return null; // should never get here
        }
        
        protected override void OnPreviewMouseMove(MouseEventArgs e)
        {
            base.OnPreviewMouseMove(e);

            if (IsBeingDragged)
            {
                if (this.Drag != null)
                {
                    Drag(this, new EventArgs());
                }
            }
        }

        protected override void OnPreviewMouseUp(MouseButtonEventArgs e)
        {
            base.OnPreviewMouseUp(e);

            IsBeingDragged = false;
            if (this.DragStop != null)
            {
                DragStop(this, new EventArgs());
            }
        }

        protected override void OnPreviewMouseDown(MouseButtonEventArgs e)
        {
            base.OnPreviewMouseDown(e);

            IsBeingDragged = true;

            if (this.DragStart != null)
            {
                DragStart(this, new EventArgs());
            }
        }
    }
}
